package com.example.democrud.user;


import com.example.democrud.ResponseVO;
import com.example.democrud.enums.ResponseEnum;
import com.example.democrud.group.Insert;
import com.example.democrud.user.pojo.UserDO;
import com.example.democrud.user.pojo.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yml
 * @since 2020-04-26
 */
@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class UserController {

    private final UserService userService;

    public UserController(UserService userService){
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseVO<UserDO> login(@RequestBody @Valid UserDTO userDTO){
        UserDO retrieve = userService.retrieve(userDTO);
        if(retrieve == null )
            return ResponseVO.error(ResponseEnum.NAME_PASSWORD_ERROR);
        return ResponseVO.successData(retrieve);
    }

    @PostMapping("/register")
    public ResponseVO<String> register(@RequestBody @Validated(Insert.class) UserDTO userDTO){
        return ResponseVO.successData(String.valueOf(userService.create(userDTO)));
    }
    @DeleteMapping("/delete/{id}")
    public ResponseVO<UserDO> delete(@PathVariable @Min(value = 0,message = "id有误请检查") @Valid Long id){
        return ResponseVO.successData(userService.delete(id));
    }

}

